using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.Inspections.Commands;

/// <summary>
/// 设备点检计划更新命令。
/// </summary>
public sealed record UpdateInspectionPlanCommand(long Id, EquipInspectionPlanDto Plan) : IRequest<IResult<bool>>;

internal sealed class UpdateInspectionPlanCommandHandler(IRepository<EquipInspectionPlan> repo) : IRequestHandler<UpdateInspectionPlanCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateInspectionPlanCommand request, CancellationToken cancellationToken)
    {
        // 同一种设备同一种点检类型只能创建一个。
        if (await repo.IsAnyAsync(m => m.MachineryId == request.Plan.MachineryId && m.InspectType == request.Plan.InspectType && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("同一种设备同一种点检类型只能创建一个");
        }

        var plan = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (plan == null)
        {
            return Result.Failure("未找到要更新的点检计划");
        }

        plan.PlanName = request.Plan.PlanName;
        plan.Schedule = request.Plan.Schedule;
        plan.Remind = request.Plan.Remind;
        plan.IsCheckFinalResult = request.Plan.IsCheckFinalResult;
        plan.Status = request.Plan.Status;
        plan.Remark = request.Plan.Remark;

        var ok = await repo.UpdateAsync(plan, m => new
        {
            m.PlanName,
            m.Schedule,
            m.Remind,
            m.IsCheckFinalResult,
            m.Status,
            m.Remark,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
